//
//  ARBalanceRechargeController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/20.
//

import UIKit
import SnapKit
import JKSwiftExtension

class ARBalanceRechargeController: ARBaseViewController {

    private let viewModel = ARRechargeCoinsViewModel()
    
    private static let cellHeight = 124.0
    private static let cellReuseId = "AR.ARBalanceRechargeController.cellreuseid"
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        loadData()
        refreshValue()
        
        ARLogManager.logPage(.purchase)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshValue), name: .userInfoUpdate, object: nil)
    }
    
    // MARK: - UI
    
    private func setupUI() {
        
        self.ar_setupNavBgImg()
        self.ar_configWhiteBackItem()
        
        self.title = ARHelper.localString("COIN SHOP")
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: ARHelper.font(18, weight: .bold)]
        }
        
        self.view.addSubview(balanceView)
        self.view.addSubview(collectionView)
        
        balanceView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(24)
            make.height.equalTo(106)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalTo(balanceView.snp.bottom).offset(24)
        }
    }
    
    private func loadData() {
        self.ar.showLoading()
        viewModel.fetchRechargeCoinsList { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            
            self?.refreshValue()
        }
    }

    @objc private func refreshValue() {
        balanceView.balanceLabel.text = String(ARUserManager.shared.userModel?.availableCoins ?? 0)
        collectionView.reloadData()
    }
    
    // MARK: - Lazy
    
    private lazy var balanceView: __ARBalanceView = {
        let view = __ARBalanceView()
        return view
    }()
    
    private lazy var collectionView: UICollectionView = {
        
        let cellSpacing = 7.0
        var cellWidth = (ARHelper.screenWidth() - 16 * 2 - cellSpacing) / 2.0
        cellWidth = floor(cellWidth)
        
        let flow = UICollectionViewFlowLayout()
        flow.itemSize = .init(width: cellWidth, height: Self.cellHeight)
        flow.scrollDirection = .vertical
        flow.minimumLineSpacing = 24
        flow.minimumInteritemSpacing = cellSpacing
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flow)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(ARRechargeCoinsCell.self, forCellWithReuseIdentifier: Self.cellReuseId)
        
        collectionView.contentInset = .init(top: 0, left: 16, bottom: ARHelper.safeBottomHeight() + 24, right: 16)
        
        collectionView.backgroundColor = .clear
        return collectionView
    }()
}

extension ARBalanceRechargeController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = self.viewModel.rechargeCoinsList[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Self.cellReuseId, for: indexPath) as! ARRechargeCoinsCell
        cell.model = model
        return cell
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.viewModel.rechargeCoinsList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        ARLogManager.logPage(.createorder)
        
        let model = self.viewModel.rechargeCoinsList[indexPath.item]
        self.ar.showLoading()
        self.viewModel.purchase(model.code) { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            // 不用做其他
        }
    }
    
}

// MARK: -

fileprivate class __ARBalanceView: UIView {
    
    var buyBtnClickCallback: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        self.backgroundColor = .clear
        
//        let width = ARHelper.screenWidth() - 16 * 2
//        let height = 106.0
        let midView = UIImageView(image: .init(named: "recharge_balance_bg")?.resizableImage(withCapInsets: .init(top: 20, left: 20, bottom: 20, right: 20), resizingMode: .stretch))
//        midView.contentMode = .scaleToFill
        self.addSubview(midView)
//        self.jk.effectViewWithAlpha(alpha: 0.8, size: .init(width: width, height: height), style: .light)
        
        midView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
//        self.layer.cornerRadius = 16
//        self.layer.masksToBounds = true
        
        let coinIconView = UIImageView(image: .init(named: "common_coin_icon"))
        let titleLabel = UILabel()
        titleLabel.font = ARHelper.font(16, weight: .regular)
        titleLabel.textColor = UIColor(hexString: "#294E69")
        titleLabel.text = ARHelper.localString("My Coins")
        
        self.addSubview(coinIconView)
        self.addSubview(titleLabel)
        self.addSubview(balanceLabel)
        
        coinIconView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(ARHelper.widthScale(28.0))
            make.width.equalTo(65)
            make.height.equalTo(65)
            make.top.equalToSuperview().offset(ARHelper.heightScale(19))
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(coinIconView.snp.right).offset(18)
            make.top.equalToSuperview().offset(24)
        }
        
        balanceLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
        }
    }
    
    lazy var balanceLabel: UILabel = {
        let label = UILabel()
        label.font = ARHelper.font(26, weight: .heavy)
        label.textColor = .init(hexString: "#1F1C1C")
        return label
    }()
    
}
